<template>
  <basic-container>
    <div class="search_form">
      <el-form ref="form" :model="queryForm" label-width="100px" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="客户:">
              <el-select id="id-business-receivable-queryForm-customerId" v-model="queryForm.customerId" clearable
                         filterable size="mini" placeholder="请选择客户名称"
                         style="width: 100%"
                         ref="customerId" @change="searchForm">
                <el-option v-for="(item,index) in receivableCustomerList"
                           :key="index" :label="item.name" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="createTime"
                style="width: 90%"
                type="daterange"
                size="mini"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="最后修改时间:">
              <el-date-picker
                v-model="updateTime"
                style="width: 90%"
                type="daterange"
                size="mini"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="min-width: 160px;display:flex;justify-content:flex-end;float: right">
            <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
              <el-button :class="upIcon" class="search-circle" @click="unfoldIcon"
                         style="margin-right: 10px"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="重置" placement="top">
              <el-button id="id-business-customer-emptyForm" :class="emptyIcon" class="search-circle"
                         @click="emptyForm"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-business-customer-searchForm" ype="primary" icon="el-icon-search" size="small"
                         @click="searchForm" style="margin-right: 0">
                搜索
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-show="searchConceal">
          <el-col :span="5">
            <el-form-item label="开票方:">
              <el-select id="id-business-receivable-queryForm-invoiceMaker" v-model="queryForm.invoiceMaker" clearable
                         filterable size="mini" placeholder="请选择所属部门"
                         style="width: 100%"
                         ref="invoiceMaker" @change="searchForm">
                <el-option v-for="(item,index) in invoiceMakerList"
                           :key="index" :label="item.name" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="计划到账日期:">
              <el-date-picker
                style="width: 90%"
                v-model="predictPaymentDate"
                type="daterange"
                size="mini"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="实际到账日期:">
              <el-date-picker
                v-model="actualPaymentDate"
                style="width: 90%"
                type="daterange"
                size="mini"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="22" v-show="searchConceal">
          <el-col :span="5">
            <el-form-item label="收款状态:">
              <el-select id="id-business-customer-queryForm-receivableStatus"
                         v-model="queryForm.receivableStatus" clearable
                         filterable size="mini" style="width: 100%"
                         ref="receivableStatus" @change="searchForm">
                <el-option label="确认数据中" value="0"/>
                <el-option label="已开票" value="1"/>
                <el-option label="已逾期" value="2"/>
                <el-option label="已收款" value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="5">-->
          <!--            <el-form-item label="状态:">-->
          <!--              <el-select id="id-business-customer-queryForm-status" v-model="queryForm.status" clearable-->
          <!--                         filterable size="mini" placeholder="请选择状态"-->
          <!--                         style="width: 150px"-->
          <!--                         ref="status" @change="searchForm">-->
          <!--                <el-option label="全部" value=""/>-->
          <!--                <el-option label="活跃" value="1"/>-->
          <!--                <el-option label="停止" value="0"/>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="5">
            <el-form-item label="付款类型:">
              <el-select id="id-business-receivable-queryForm-paymentType"
                         v-model="queryForm.paymentType" clearable
                         filterable size="mini" style="width: 100%"
                         ref="paymentType" @change="searchForm">
                <el-option label="预付" value="0"/>
                <el-option label="后付" value="1"/>
                <el-option label="退税" value="2"/>
                <el-option label="退款" value="3"/>
                <el-option label="充值" value="4"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="数据已处理:">
              <el-select id="id-business-receivable-queryForm-proceedStatus"
                         v-model="queryForm.proceedStatus" clearable
                         filterable size="mini" style="width: 100%"
                         ref="proceedStatus" @change="searchForm">
                <el-option label="已处理" value="1"/>
                <el-option label="未处理" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="账单月份:">
              <el-date-picker
                v-model="occurMonth"
                style="width: 90%"
                type="monthrange"
                size="mini"
                value-format="yyyy-MM"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20" v-show="searchConceal">

          <el-col :span="5">
            <el-form-item label="所属部门:">
              <el-select id="id-business-receivable-queryForm-dept" v-model="queryForm.dept" clearable
                         filterable size="mini" placeholder="请选择所属部门"
                         style="width: 100%"
                         ref="dept" @change="searchForm">
                <el-option v-for="(item,index) in deptList"
                           :key="index" :label="item.dictValue" :value="item.dictKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="实际金额($):">
              <el-input id="id-business-receivable-queryForm-actualAmount" size="mini" placeholder="查询>=某金额的数据"
                        v-model="queryForm.actualAmount">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="实体名称:">
              <el-input id="id-business-receivable-queryForm-actualAmount" size="mini" placeholder="请输入"
                        v-model="queryForm.entityName">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <avue-crud :option="option"
               :table-loading="loading"
               :view-name="'receivable'"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :row-class-name-rollback="getRowClassName"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <!--      <template slot-scope="{row}" slot="status">-->
      <!--        <el-select v-model="row.status"-->
      <!--                   size="mini"-->
      <!--                   @change="changeStatus(row)">-->
      <!--          <el-option label="停止" :value="0"></el-option>-->
      <!--          <el-option label="活跃" :value="1"></el-option>-->
      <!--        </el-select>-->
      <!--      </template>-->
      <template slot="createTimeHeader" slot-scope="{column}">
        <div class="hanDer">{{ (column || {}).label }}</div>
      </template>

      <template slot-scope="{row}" slot="receivableStatus">
        <el-select v-model="row.receivableStatus"
                   size="mini"
                   :disabled="!roles.admin"
                   @change="changeStatus(row)">
          <el-option label="确认数据中" :value="0"></el-option>
          <el-option label="已开票" :value="1"></el-option>
          <el-option label="已逾期" :value="2"></el-option>
          <el-option label="已收款" :value="3"></el-option>
        </el-select>
      </template>

      <template slot-scope="{row}" slot="proceedStatus">
        <el-select v-model="row.proceedStatus"
                   size="mini"
                   @change="changeStatus(row)">
          <el-option label="未处理" :value="0"></el-option>
          <el-option label="已处理" :value="1"></el-option>
        </el-select>
      </template>

      <template slot-scope="{row}" slot="paymentType">
        <span>{{ getPaymentType(row.paymentType) }}</span>
      </template>

      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   id="id-finance-receivable-handleAdd"
                   icon="el-icon-plus"
                   plain
                   v-if="permission.receivable_add"
                   @click="handleAdd">新 增
        </el-button>
        <el-button id="id-finance-receivable-handleDelete"
                   type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permissionList.delBtn"
                   @click="handleDelete">删 除
        </el-button>
        <el-button id="id-finance-receivable-handleDelete"
                   type="success"
                   size="small"
                   icon="el-icon-edit"
                   plain
                   v-if="roles.admin"
                   @click="batchUpdateStatus">修改收款状态
        </el-button>
        <el-button id="id-finance-receivable-handleExport"
                   type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   :disabled="!(selectionList.length > 0)"
                   v-if="permissionList.excelBtn"
                   @click="handleExport">导 出
        </el-button>
        <el-button id="id-finance-receivable-summary"
                   type="danger"
                   size="small"
                   icon="el-icon-download"
                   plain
                   :disabled="!(selectionList.length > 0)"
                   @click="handleSummary">求 和
        </el-button>
        <el-button id="id-finance-receivable-exportInvoice"
                   type="warning"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permissionList.excelBtn"
                   @click="handleExportInvoice">下载发票
        </el-button>
        <el-button id="id-finance-receivable-progress"
                   type="primary"
                   size="small"
                   icon="el-icon-document"
                   plain
                   v-if="permissionList.viewBtn"
                   @click="viewReceivableProgress">收支进展
        </el-button>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-tooltip content="查看" placement="top">
          <el-button size="small" icon="el-icon-view" type="text" @click="rowView(scope.row,scope.index)"
                     :disabled="!(permissionList.viewBtn)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="编辑" placement="top">
          <el-button icon="el-icon-edit" type="text" @click="rowEdit(scope.row,scope.index)"
                     :disabled="!(permissionList.editBtn)"></el-button>
        </el-tooltip>
        <el-tooltip content="复制" placement="top">
          <el-button icon="el-icon-document-copy" type="text" @click="rowCopy(scope.row,scope.index)"
                     :disabled="!(permissionList.editBtn)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="删除" placement="top">
          <el-button icon="el-icon-delete" type="text" @click="rowDel(scope.row,scope.index)"
                     :disabled="!(scope.row.funcFlag != 'used' && permissionList.delBtn)"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>

    <!--    批量修改状态弹窗-->
    <el-dialog
      title="批量修改状态"
      :visible.sync="batchChangeStatusVisible"
      width="30%"
      append-to-body>
      <el-row>
        收款状态：
        <el-select v-model="statusValues"
                   size="mini">
          <el-option label="确认数据中" :value="0"></el-option>
          <el-option label="已开票" :value="1"></el-option>
          <el-option label="已逾期" :value="2"></el-option>
          <el-option label="已收款" :value="3"></el-option>
        </el-select>
      </el-row>
      <div style="margin-top: 20px">已选数据：</div>
      <el-table
        :data="selectionList"
        style="width: 100%">
        <el-table-column
          prop="customerName"
          label="客户">
        </el-table-column>
        <el-table-column
          prop="occurMonth"
          label="账单月份">
        </el-table-column>
        <el-table-column
          prop="receivableStatus"
          label="收款状态">
          <template v-slot="{row}">
            {{ getReceivableStatusText(row.receivableStatus) }}
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button @click="batchChangeStatusVisible = false">取 消</el-button>
    <el-button type="primary" @click="batchChange">确 定</el-button>
  </span>
    </el-dialog>


    <el-drawer size="60%" :title="'收支进展'" :visible.sync="progressDrawerVisible" :modal-append-to-body="false"
               style="width:100%;" :close-on-press-escape="false" :wrapperClosable="false"
               :close-on-click-modal="false" :before-close="handlerProgressDrawerClose" :append-to-body="true">
      <el-table :data="selectionList" style="margin: 10px;">
        <el-table-column prop="customerName" label="客户">
          <template v-slot="{row}">
            {{ row.customerName }}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceMaker" label="开票方">
          <template v-slot="{row}">
            {{ row.invoiceMakerName }}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceName" label="发票名">
          <template v-slot="{row}">
            {{ row.invoiceName }}
          </template>
        </el-table-column>
        <el-table-column prop="occurMonth" label="账单月份">
          <template v-slot="{row}">
            {{ row.occurMonth }}
          </template>
        </el-table-column>
        <el-table-column prop="receivableStatus" label="收款状态">
          <template v-slot="{row}">
            {{ getReceivableStatusText(row.receivableStatus) }}
          </template>
        </el-table-column>
        <el-table-column prop="dept" label="所属部门">
          <template v-slot="{row}">
            {{ row.dept }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentType" label="付款类型">
          <template v-slot="{row}">
            {{ getPaymentType(row.paymentType) }}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceAmount" label="发票金额($)">
          <template v-slot="{row}">
            {{ row.invoiceAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="predictPaymentDate" label="计划到账日期">
          <template v-slot="{row}">
            {{ row.predictPaymentDate }}
          </template>
        </el-table-column>
        <el-table-column prop="proceedStatus" label="数据处理">
          <template v-slot="{row}">
            {{ getProceedStatus(row.proceedStatus) }}
          </template>
        </el-table-column>

      </el-table>
      <div class="comment-body" v-for="item in progressList" :key="item.id">
        <el-row :gutter="20" class="comment-main">
          <el-col :span="2" style="text-align: right">
            <el-avatar icon="el-icon-user-solid"></el-avatar>
          </el-col>
          <el-col :span="4" style="line-height: 35px">{{ item.createUserName }}</el-col>
          <el-col :span="18" class="comment-content">
            <div v-html="formatHtml(item.content)"></div>
          </el-col>
          <el-col :span="20" :offset="6" class="comment-time"><span>{{ item.createTime }}</span>
          </el-col>
        </el-row>
      </div>
      <div style="height: 250px;margin: 20px;">
        <quill-editor style="height: 180px;" v-model="progressContent" :options="editorOptions"></quill-editor>
        <div style="margin-top: 60px">
          <el-button size="mini" type="primary" icon="el-icon-circle-check" @click="handleProgressSubmit">保存</el-button>
          <el-button size="mini" icon="el-icon-circle-close" @click="progressDrawerVisible = false;">取消</el-button>
        </div>
      </div>

    </el-drawer>
    <el-drawer size="60%" :title="drawerTitle" :visible.sync="drawerVisible" :modal-append-to-body="false"
               style="width:100%;" :close-on-press-escape="false" :wrapperClosable="false"
               :close-on-click-modal="false" :before-close="handlerDrawerClose" :append-to-body="true">
      <el-form ref="editForm" :model="form" label-width="150px" style="width: 90%;margin: 0 auto" :rules="rules">
        <el-row :gutter="20" style="display: flex;flex-wrap: wrap">
          <el-col :span="item.span || 12" v-for="(item,index) in option.column" :key="index" v-if="drawerTitle === '查 看'
          ? (item.viewDisplay === false ? false : true) : drawerTitle ==='新 增' ? (item.addDisplay === false ? false : true):
          (item.editDisplay === false ? false : true)">
            <el-form-item :label="item.label" :prop="item.prop"
                          :style="drawerTitle == '查 看' ? 'margin-bottom: 0px' : 'margin-bottom: 22px'">
              <el-select clearable filterable
                         :disabled="drawerTitle === '查 看' || item.selectDisable || disableProps.includes(item.prop)"
                         style="width: 100%" size="mini"
                         v-if="item.type === 'select'"
                         @change="item.callback&&item.callback($event)"
                         :multiple="!!item.multiple"
                         v-model="form[item.prop]">
                <el-option v-for="it in item.dicData" :key="item.props ? it[item.props.value] : it.value"
                           :label="item.props ? it[item.props.label] : it.label"
                           :value="item.props ? it[item.props.value] : it.value"
                ></el-option>
              </el-select>
              <el-switch v-if="item.type === 'switch'" v-model="form[item.prop]" :active-value='1' :inactive-value='0'
                         :disabled="drawerTitle === '查 看'">
              </el-switch>
              <span v-if="item.type === 'text'">{{ curBriefName }}</span>
              <el-input v-if="item.type === 'textarea'" type="textarea" :disabled="drawerTitle === '查 看'" size="mini"
                        v-model="form[item.prop]" :autosize="{ minRows: 5 }" maxlength="500" show-word-limit></el-input>
              <el-input maxlength="100" :disabled="drawerTitle === '查 看'" v-if="item.type === 'input' || !item.type"
                        size="mini" v-model="form[item.prop]" :readonly="item.readonly"></el-input>
              <el-input type="number" maxlength="100"
                        :disabled="drawerTitle === '查 看' || disableProps.includes(item.prop)"
                        v-if="item.type === 'number'"
                        size="mini" v-model="form[item.prop]"></el-input>
              <el-date-picker
                v-if="item.type === 'datemonth'"
                id="id-finance-receivable-occurMonth"
                v-model="form[item.prop]"
                type="month"
                value-format="yyyy-MM"
                unlink-panels
                size="mini"
                :picker-options="pickerOptions"
                style="width: 100%"
                @change="item.callback&&item.callback($event)"
                :disabled="drawerTitle === '查 看' || disableProps.includes(item.prop)">
              </el-date-picker>

              <el-date-picker
                v-if="item.type === 'datedate'"
                id="id-finance-receivable-predictPaymentDate"
                v-model="form[item.prop]"
                type="date"
                value-format="yyyy-MM-dd"
                unlink-panels
                size="mini"
                :picker-options="pickerOptions"
                style="width: 100%"
                :disabled="drawerTitle === '查 看' || disableProps.includes(item.prop)">
              </el-date-picker>
              <el-row v-if="item.type === 'uploadfile'">
                <el-col v-show="drawerTitle !== '查 看'" :span="12">
                  <!--                  <file-uploader ref="fileUploader" :limit="1"-->
                  <!--                                 :file-list="appendFileList"-->
                  <!--                                 @uploadFinished="uploadFinished"-->
                  <!--                                 @fileDeleted="fileDeleted"></file-uploader>-->
                  <creative-upload-prod-obs v-if="item.type === 'uploadfile'"
                                            :file-map="appendFileList"
                                            plug-in-unit="10" :limit="10"
                                            ref="beeltesUpload"></creative-upload-prod-obs>
                  <!--                  <creative-upload ref="upload" mode="edit" :max="5" :data="appendFileList"></creative-upload>-->


                </el-col>
                <el-col :span="24">
                  <div style="margin-top:50px; margin-left:-25px; display: grid;grid-template-columns: 1fr 1fr 1fr 1fr 1fr">
                    <div v-for="(item,index) in appendFileList" :key="index" class="product-upload"
                         style="margin-left: 30px">
                      <div>
                        <ul style="margin-top: 10px" class="el-upload-list el-upload-list--picture-card">
                          <li class="el-upload-list__item is-ready" style="height: 120px;width: 120px">
                        <span v-if="item.type === 'image' || item.type === 'video' || item.type ===''">
                          <el-progress v-if="item.progress !== 100" type="circle"
                                       :percentage="item.progress"></el-progress>
                          <span v-if="item.url === '-1'">上传失败</span>
                          <img v-if="item.type===''" style="height:120px;width:140px;margin-top:5px;"
                               class="el-upload-list__item-thumbnail creative" src="/img/icon/excel.png" alt="">
                          <img v-if="item.type === 'image' && item.progress === 100 && item.url !=='-1' "
                               class="el-upload-list__item-thumbnail creative" :src="item.url" alt="">
                          <video v-if="item.type  === 'video' && item.progress === 100 && item.url !=='-1' "
                                 class="el-upload-list__item-thumbnail creative" :src="item.url"></video>
                         <span class="el-upload-list__item-actions">
<!--                            <span v-if="item.type  === 'video'" class="el-upload-list__item-preview"><i-->
                           <!--                              class="el-icon-video-camera"></i></span>-->
                            <span v-if="drawerTitle !== '新 增'" class="el-upload-list__item-preview"
                                  @click="handleQiniuDownload(item)"><i
                              class="el-icon-download"></i></span>
                            <span v-if="item.type === 'image'" class="el-upload-list__item-preview"><i
                              class="el-icon-search" @click="checkImage(item)"></i></span>
                            <span v-if="item.type === ''" class="el-upload-list__item-delete"
                                  @click="view(item)"><i
                              class="el-icon-view"></i></span>
                            <span v-if="drawerTitle!=='查 看'" class="el-upload-list__item-delete"
                                  @click="handleRemove(item)"><i
                              class="el-icon-delete"></i></span>
                          </span>
                        </span>
                          </li>
                        </ul>
                      </div>
                      <!--                    <div style="width: 120px; margin-top: -20px; overflow-wrap: anywhere; line-height: 25px;">-->
                      <!--                        {{ item.name }}-->
                      <!--                    </div>-->
                    </div>
                  </div>

                </el-col>
              </el-row>
              <!--              <creative-upload v-if="item.type === 'uploadfile'"-->
              <!--                               :init-file-list="getFileList()"-->
              <!--                               ref="upload" mode="edit" :max="5" :data="form"></creative-upload>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-dialog
          :visible.sync="visble"
          width="50%"
          :close-on-click-modal="false"
          append-to-body>
          <iframe :src="visbleURL" frameborder="0" width="100%" height="600"></iframe>
        </el-dialog>
        <el-dialog
          :visible.sync="imageCheck"
          width="50%"
          :close-on-click-modal="false"
          append-to-body>
          <img style="width: 80%;height:70%" :src="imageUrl">
        </el-dialog>

        <!--<el-row>-->
        <!--<el-table :data="financeItemList" style="margin: 10px;">-->
        <!--  <el-table-column v-if="drawerTitle !== '新 增'" width="100px" prop="id" label="ID">-->
        <!--    <template v-slot="{row}">-->
        <!--      <el-input :disabled="drawerTitle === '查 看'" size="mini" v-model="row.shortId"></el-input>-->
        <!--    </template>-->
        <!--  </el-table-column>-->
        <!--  <el-table-column prop="detail" label="明细">-->
        <!--    <template v-slot="{row}">-->
        <!--      <el-input :disabled="drawerTitle === '查 看'" size="mini" v-model="row.detail"></el-input>-->
        <!--    </template>-->
        <!--  </el-table-column>-->
        <!--  <el-table-column prop="amount" label="金额($)" width="200px">-->
        <!--    <template v-slot="{row}">-->
        <!--      <el-input :disabled="drawerTitle === '查 看'"-->
        <!--                onblur="if (this.value < 0) this.value = 0;"-->
        <!--                type="number" size="mini" v-model="row.amount"></el-input>-->
        <!--    </template>-->
        <!--  </el-table-column>-->
        <!--  <el-table-column-->
        <!--    width="50">-->
        <!--    <template v-slot="{row, column, $index}">-->
        <!--      <i v-show="drawerTitle !== '查 看'" class="el-icon-delete" style="cursor: pointer"-->
        <!--         @click="removeFinanceItem($index)"></i>-->
        <!--    </template>-->
        <!--  </el-table-column>-->
        <!--</el-table>-->
        <!--<el-link type="primary" @click="addFinanceItem" v-show="drawerTitle != '查 看'">+ 添加</el-link>-->
        <!--</el-row>-->
        <div class="app-item-container" v-for="appId in form.appIds">
          <div class="app-header">
            <el-form :inline="true" :model="appSelectMap[appId].data" label-width="60px" size="mini">
              <el-form-item>
                {{ findAppName(appId) }}
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="appSelectMap[appId].data.byCountryInvoice" @change="handleChangeAreaCheck(appId)">
                  按地区开票
                </el-checkbox>
              </el-form-item>
            </el-form>
          </div>
          <div class="app-table">
            <el-table
              :data="appSelectMap[appId].data.byCountryInvoice ? appSelectMap[appId].data.byCountry : appSelectMap[appId].data.byAll"
              border
              :ref="appId+'table'"
              style="width: 100%"
              @selection-change="handleSelectionChange($event,appId)">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                prop="platformId"
                :filters="appSelectMap[appId].data.platformIdList"
                :filter-method="filterHandler"
                label="账户id">
              </el-table-column>
              <el-table-column
                prop="accountName"
                label="账户名">
              </el-table-column>
              <el-table-column
                prop="platform"
                :filters="appSelectMap[appId].data.platformList"
                :filter-method="filterHandler"
                label="媒体">
              </el-table-column>
              <el-table-column
                prop="country"
                :filters="appSelectMap[appId].data.countryList"
                :filter-method="filterHandler"
                label="地区">
                <template v-slot="{ row }">
                  {{ row.country === 'all' ? '全部' : row.country }}
                </template>
              </el-table-column>
              <el-table-column
                prop="cost"
                label="花费">
                <template v-slot="{ row }">
                  <template v-if="!row.editCost">
                    <span>{{ row.cost }}</span>
                    <el-button type="text" size="mini" icon="el-icon-edit"
                               @click="row.editCost = true"></el-button>
                  </template>
                  <el-input size="mini" v-else v-focus v-model="row.cost"
                            oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} if(value.contains('-')){value = 0}"
                            @blur="handleBlurCost(row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="serviceFee"
                label="服务费(%)">
                <template v-slot="{ row }">
                  <template v-if="!row.editServiceFee">
                    <span>{{ row.serviceFee }}</span>
                    <el-button type="text" size="mini" icon="el-icon-edit"
                               @click="row.editServiceFee = true"></el-button>
                  </template>
                  <el-input size="mini" v-else v-focus v-model="row.serviceFee"
                            oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} if(value.contains('-')){value = 0}"
                            @blur="handleBlurServiceFee(row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="includeServiceFee"
                label="包含花费">
                <template v-slot="{ row }">
                  <el-checkbox v-model="row.includeServiceFee" @change="changeIncludeServiceFee(row)"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                prop="invoiceAmount"
                label="发票金额">
                <template v-slot="{ row }">
                  <template v-if="!row.editInvoiceAmount">
                    <span>{{ row.invoiceAmount }}</span>
                    <el-button type="text" size="mini" icon="el-icon-edit"
                               @click="row.editInvoiceAmount = true"></el-button>
                  </template>
                  <el-input size="mini" v-else v-focus v-model="row.invoiceAmount"
                            oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} if(value.contains('-')){value = 0}"
                            @blur="handleBlurinvoiceAmount(row)"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div style="padding: 20px;">
          <el-button v-show="drawerTitle != '查 看'" size="mini" type="primary" icon="el-icon-circle-check"
                     @click="handleForm">保存
          </el-button>
          <el-button size="mini" icon="el-icon-circle-close" @click="handlerDrawerClose">退出</el-button>
        </div>
      </el-form>
    </el-drawer>
    <el-dialog title="选择发票格式"
               append-to-body
               :visible.sync="selectSealBox"
               width="545px">
      <div style="margin-bottom: 50px; margin-left: 50px;">
        <el-radio-group v-model="invoiceFormat">
          <el-radio :key="0" :label="0">Word</el-radio>
          <el-radio :key="1" :label="1">Pdf</el-radio>
        </el-radio-group>
      </div>
      <div style="margin-bottom: 30px; margin-left: 50px;">
        <el-radio-group v-model="currentSeal">
          <el-radio v-for="item in sealList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button @click="selectSealBox = false">取 消</el-button>
            <el-button id="aaaaaa" type="success" @click="exportInvoice()">确 定</el-button>
          </span>
    </el-dialog>
    <div id="downloadExcel"></div>
  </basic-container>
</template>

<script>
import {
  getReceivableList,
  addReceivable,
  removeReceivable,
  updateReceivable,
  changeReceivableStatus,
  getReceivableCustomers,
  getInvoiceMakers,
  addProgress,
  getProgressList,
  downloadInvoice,
  getFinanceEntityList,
  exportExcel3,
  getEntityList,
  getAppSelectbyCostomer, getAccountCostDetails, isFinanceRole
} from "@/api/finance/receivable";
import creativeUpload from "/src/components/beetles-upload/creative_upload";
import creativeUploadProdObs from "@/components/beetles-upload/creative_upload_prod_obs";
import {deepClone, exportExcel} from "@/util/util";
import {mapGetters} from "vuex";
import BeetlesTable from "@/components/basic-components/beetles-table";
import axios from 'axios'
import fileDownload from 'js-file-download'

import {getDept, getFinanceItemList, getCustomerList} from "@/api/finance/commonApi";
import {exportExcel2} from "@/api/offer/creativeperformance";
import FileUploader from "../../components/beetles-upload/file_uploader";
import _ from 'lodash'


export default {
  components: {
    FileUploader,
    BeetlesTable,
    creativeUpload,
    creativeUploadProdObs
  },
  data() {
    return {
      visble: false,
      visbleURL: '',
      index: 0,
      imageCheck: false,
      imageUrl: '',
      editData: [],
      invoiceMakerList2: [],
      selectSealBox: false,
      financeItemList: [{id: "", detail: "", amount: ""}],
      entityList: [],
      appendFileList: [],
      deptList: [],
      pickerOptions: {},
      sealList: [
        {label: '无', value: 0},
        {label: '香港圆章', value: 1},
        {label: '香港方章', value: 2},
        {label: '新加坡圆章', value: 3},
      ],
      invoiceFormat: 0,
      currentSeal: 0,
      customerList: [{'name': '', 'key': '', 'data': ''}],
      receivableCustomerList: [],
      invoiceMakerList: [],
      progressList: [],
      upIcon: 'el-icon-arrow-down',
      searchConceal: false,
      rules: {},
      form: {
        appIds: [],
        invoiceAmount: ''
      },
      progressContent: '',
      createTime: [],
      updateTime: [],
      predictPaymentDate: [],
      actualPaymentDate: [],
      occurMonth: [],
      editorOptions: {
        placeholder: '请输入收支进展',
        modules: {
          toolbar: {
            container: [['bold', 'italic', 'underline', 'strike'], ['image']]
          }
        },
      },
      queryForm: {
        customerId: '',
        dept: '',
        receivableStatus: '',
        paymentType: '',
        proceedStatus: '',
        invoiceMaker: '',
        startCreateTime: '',
        endCreateTime: '',
        startUpdateTime: '',
        endUpdateTime: '',
        startPredictPaymentDate: '',
        endPredictPaymentDate: '',
        startActualPaymentDate: '',
        endActualPaymentDate: '',
        startOccurMonth: '',
        endOccurMonth: '',
        actualAmount: '',
        entityName: '',
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      emptyIcon: 'el-icon-delete',
      drawerTitle: '',
      drawerVisible: false,
      progressDrawerVisible: false,
      managerList: [],
      selectionList: [],
      createUserList: [],
      curBriefName: "",
      curBankName: "",
      financeRoles: true,
      batchChangeStatusVisible: false,
      statusValues: null,
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 120,
        selection: true,
        dialogClickModal: false,
        dialogWidth: 1200,
        column: [
          {
            label: "ID",
            width: 50,
            prop: "shortId",
            overHidden: true,
            fixed: true,
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false,
          },
          {
            label: "客户",
            type: 'select',
            prop: "customerId",
            // dicData: this.customerList,
            props: {
              label: "name",
              value: "key",
              data: "data"
            },

            rules: [{
              required: true,
              message: "请选择客户",
              trigger: "change"
            }],
            overHidden: true,
            fixed: true,
            // hide: true,
            showColumn: false,
            callback: this.getAppSelectbyCostomer
          },
          {
            label: "客户",
            prop: "customerName",
            overHidden: true,
            fixed: true,
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false,
          },
          {
            label: "客户全称",
            type: 'text',
            dataType: 'string',
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: true,
          },
          {
            label: "开票方",
            type: 'select',
            prop: "invoiceMaker",
            // dicData: this.customerList,
            dicData: this.invoiceMakerList2,
            props: {
              label: "name",
              value: "id",
            },
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: false,
            rules: [{
              required: true,
              message: "请选择开票方",
              trigger: "change"
            }],
            callback: this.invoiceMakerChanged
          },

          {
            label: "发票名",
            prop: "invoiceName",
            overHidden: true,
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false,
          },
          // {
          //   label: "开票方",
          //   prop: "invoiceMakerName",
          //   addDisplay: false,
          //   viewDisplay: false,
          //   editDisplay: false,
          // },
          {
            label: "实体名称",
            prop: "entityName",
            type: 'select',
            hide: true,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            dicData: [],
            rules: [{
              required: true,
              message: "请选择实体",
              trigger: "change"
            }],
            props: {
              label: "entityName",
              value: "id"
            },
            callback: this.bankNameChange
          },
          {
            label: "收款银行",
            prop: "entityId",
            type: 'select',
            hide: true,
            selectDisable: true,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            dicData: [],
            rules: [{
              required: true,
              message: "请选择收款银行",
              trigger: "change"
            }],
            props: {
              label: "bankName",
              value: "id"
            },
          },
          {
            label: "收款状态",
            type: 'select',
            prop: "receivableStatus",
            width: 120,
            // financeEdit: this.financeRoles,
            dicData: [
              {label: '确认数据中', value: 0},
              {label: '已开票', value: 1},
              {label: '已逾期', value: 2},
              {label: '已收款', value: 3}
            ],
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "所属部门",
            type: 'select',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            prop: "dept",
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "数据处理",
            type: 'select',
            prop: "proceedStatus",
            addDisplay: true,
            width: 120,
            dicData: [
              {label: '未处理', value: 0},
              {label: '已处理', value: 1}
            ],
          },
          {
            label: "付款类型",
            type: 'select',
            width: 80,
            prop: "paymentType",
            addDisplay: true,
            dicData: [
              {label: '预付', value: 0},
              {label: '后付', value: 1},
              {label: '返点', value: 2},
              {label: '退款', value: 3},
              {label: '充值', value: 4},
            ],
          },
          {
            label: "实际金额($)",
            type: 'number',
            prop: "actualAmount",
            // financeEdit: this.financeRoles,
            width: 100,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "金额(RMB)",
            type: 'number',
            prop: "amountRmb",
            width: 100,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "手续费",
            prop: "serviceFee",
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: true
          },
          {
            label: "开票日期",
            type: "datedate",
            prop: "invoiceDate",
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false,
          },
          {
            label: "回款天数",
            type: "datedate",
            prop: "receivableDays",
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false,
          },
          {
            label: "计划到账日期",
            type: "datedate",
            prop: "predictPaymentDate",
            width: 100,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "实际到账日期",
            type: "datedate",
            width: 100,
            // financeEdit: this.financeRoles,
            prop: "actualPaymentDate",
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "选择APP",
            type: 'select',
            prop: "appIds",
            multiple: true,
            addDisplay: true,
            hide: true,
            props: {
              label: "name",
              value: "id"
            },
            dicData: [],
            rules: [{type: 'array', required: true, message: '请至少选择一个APP', trigger: 'change'}],
            callback: this.handleChangeApp
          },
          {
            label: "账单月份",
            prop: "occurMonth",
            type: 'datemonth',
            valueFormat: 'yyyy-MM-dd',
            rules: [
              {
                required: true,
                message: '请选择账单月份',
                trigger: 'blur'
              }
            ],
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            callback: this.handleChangeOccurMonth
          },
          {
            label: "发票金额(USD)",
            prop: "invoiceAmount",
            type: 'input',
            width: 100,
            readonly: true,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
          },
          {
            label: "创建人",
            prop: "createUserName",
            filterable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "创建时间",
            prop: "createTime",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            overHidden: true
          },
          {
            label: "附件",
            span: 24,
            type: 'uploadfile',
            prop: "accessory",
            addDisplay: true,
            editDisplay: true,
            hide: true,
            overHidden: true
          },
        ]
      },
      data: [],
      currOpRowId: '',
      // app map列表
      appSelectMap: {
        // app1: {
        //   query: {},
        //   data: [{
        //     accountId: '334234',
        //     accountName: '木星',
        //     plateform: 'fecebook',
        //     area: '埃及',
        //     spend: 111,
        //     service: 2,
        //     cover: true,
        //     amount: 33
        //   }]
        // }
      },
      curAppIds: [],
      appList: []
    };
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector("input").focus()
      }
    }
  },
  computed: {
    ...mapGetters(["permission", "roles", "userInfo"]),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: this.vaildData(this.permission.receivable_view),
        delBtn: this.vaildData(this.permission.receivable_delete),
        editBtn: this.vaildData(this.permission.receivable_edit),
        excelBtn: this.vaildData(this.permission.receivable_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    disableProps() {
      if (this.financeRoles) {
        return []
      } else {
        return ['receivableStatus', 'actualAmount', 'actualPaymentDate']
      }
    }
  },
  watch: {
    'form.customerId': {
      handler(val) {
        this.curBriefName = this.option.column[1].dicData.find(item => item.key === val).data
      }
    },
  },
  mounted() {
    // const{data:res} = await getEntityList(1,-1)
    // this.invoiceMakerList2 = res.data.records
    // isFinanceRole().then((res)=>{
    //   // console.log(res)
    //   this.financeRoles = res.data.success ? false : true
    // })
  },
  async created() {
    console.log('roles', this.roles)
    const res = await isFinanceRole()
    this.financeRoles = res.data.success
    this.init();
    this.buildSearch();
    // this.getAppSelectbyCostomer()
  },
  methods: {
    uploadFinished(url) {
      // console.log("this.accountForm.licenseImage" + url)
      // this.appendFileList = url;
    },
    fileDeleted(url) {
      console.log("this.accountForm.fileDeleted" + url)
      // this.appendFileList = [];
    },
    validAmount() {
      if (this.value < 0) this.value = 0;
    },
    getFileList() {
      let fileList = [];
      this.appendFileList.forEach((appendFile) => {
        fileList.push({
          name: appendFile.name,
          url: appendFile.url,
        })
      });
      return fileList;
    },
    invoiceMakerChanged(value) {
      if (value != "") {
        this.$set(this.form, 'entityId', '')
        getFinanceEntityList(value).then(res => {
          // this.entityList = res.data.data;
          const column = this.findObject(this.option.column, "entityId");
          column.dicData = res.data.data;
        });
        this.$set(this.form, 'entityName', '')
        getFinanceEntityList(value).then((res) => {
          const column = this.findObject(this.option.column, "entityName");
          column.dicData = res.data.data;
        })
      }
    },
    bankNameChange() {
      console.log('form', this.form)
      this.form.entityId = this.form.entityName
      // getFinanceEntityList(this.form.customerId).then(res => {
      //   this.form.entityId = res.data.data.find(item=>item.id===this.form.entityName)['']
      // });

    },
    removeFinanceItem(index) {
      if (this.financeItemList.length == 1) {
        this.$message({
          type: 'warning',
          message: '最后一条了!'
        });
        return
      }
      this.financeItemList.splice(index, 1)
    },
    addFinanceItem() {
      this.financeItemList.push(
        {
          detail: '',
          amount: ''
        }
      )
    },
    //删除素材
    handleRemove(v) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log('确认',confirmButtonText)
        console.log(v)
        console.log('z', this.$refs.beeltesUpload)
        this.$refs.beeltesUpload[0].removeByUid(v.uid);
        console.log('sss')
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        console.log('取消')
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchChange() {
      this.selectionList.forEach((value, index) => {
        value['receivableStatus'] = this.statusValues
      })
      console.log(this.selectionList)
      batchChangeStatus(this.selectionList).then(() => {
        this.$message.success('修改成功')
      }).finally(() => {
        this.batchChangeStatusVisible = false
        this.refreshChange()
      })
    },
    getReceivableStatusText(status) {
      if (status == 0) return "确认数据中";
      if (status == 1) return "已开票";
      if (status == 2) return "已逾期";
      if (status == 3) return "已收款";
    },
    formatHtml(origin) {
      return origin.replace(/\n|\r/g, '<br/>')
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    productNameString(productName) {
      let nameList = []
      if (productName !== '') {
        nameList = productName.split(",")
      }
      return nameList
    },
    changeStatus(row) {
      changeReceivableStatus(row).then(() => {
        this.$message.success("状态已修改")
      })
    },
    /**
     * 新增
     */
    handleAdd() {
      this.optionRules()
      this.form = {
        phone: '',
        email: '',
        receivableStatus: 0,
        dept: 'OP',
        proceedStatus: 0,
        paymentType: 0,
        invoiceAmount: ''
      }
      this.progressList = '';
      this.curBriefName = '';
      this.financeItemList = [{id: "", detail: "", amount: ""}];
      this.drawerTitle = '新 增';
      this.drawerVisible = true;

      this.appendFileList = []
      this.setDefaultInvoiceMaker()
    },
    progressView(row) {
      this.progressDrawerVisible = true

      getProgressList(row.id).then((res) => {
        this.progressList = res.data.data
      })
    },
    /**
     * 查看
     */
    rowView(row) {
      console.log(row)
      this.form = row;
      this.getAppSelectMapById()
      this.beforeOpen();
      this.drawerTitle = '查 看';
      this.drawerVisible = true;

      getFinanceEntityList(row.invoiceMaker).then((res) => {
        const column = this.findObject(this.option.column, "entityId");
        column.dicData = res.data.data;
      })
      getFinanceEntityList(row.invoiceMaker).then((res) => {
        const column = this.findObject(this.option.column, "entityName");
        column.dicData = res.data.data;
      })
      this.appendFileList = []
      if (this.form.accessory != '' || this.form.accessory != undefined) {
        let fileList = JSON.parse(this.form.accessory)
        fileList.map(item => {
          this.appendFileList.push({
            'name': item.name,
            'url': item.url,
            'type': this.creativeType(item.url),
            'progress': 100
          })
        })
      }

      getProgressList(this.form.id).then((res) => {
        this.progressList = res.data.data
      })

      // getFinanceItemList(this.form.id).then((res) => {
      //   this.financeItemList = res.data.data
      //   if (this.financeItemList.length == 0)
      //     this.financeItemList = [{id: "", detail: "", amount: ""}];
      // })
    },
    /**
     * 编辑
     */
    rowEdit(row) {
      console.log(row)
      this.rules = {}
      // this.curBriefName = '';
      this.form = deepClone(row);
      // 获取app账单内容
      this.getAppSelectMapById()
      this.beforeOpen();
      this.drawerTitle = '编 辑';
      this.drawerVisible = true;
      this.optionRules()

      this.appendFileList = []
      if (this.form.accessory != '' || this.form.accessory != undefined) {
        let fileList = JSON.parse(this.form.accessory)
        fileList.map(item => {
          this.appendFileList.push({
            'name': item.name,
            'url': item.url,
            'type': this.creativeType(item.url),
            'progress': 100
          })
        })
      }
      getFinanceEntityList(row.invoiceMaker).then((res) => {
        const column = this.findObject(this.option.column, "entityId");
        column.dicData = res.data.data;
      })
      getFinanceEntityList(row.invoiceMaker).then((res) => {
        const column = this.findObject(this.option.column, "entityName");
        column.dicData = res.data.data;
      })

      getFinanceItemList(this.form.id).then((res) => {
        this.financeItemList = res.data.data
        if (this.financeItemList.length == 0)
          this.financeItemList = [{id: "", detail: "", amount: ""}];
      })
    },
    rowCopy(row) {
      console.log(row)
      this.rules = {}
      // this.curBriefName = '';
      this.form = deepClone(row);
      delete this.form.shortId
      console.log(this.form)
      this.form.receivableStatus = ''
      this.form.actualPaymentDate = ''
      this.form.actualAmount = ''
      this.beforeOpen();
      this.drawerTitle = '复 制';
      this.drawerVisible = true;
      this.optionRules()

      this.appendFileList = []
      if (this.form.accessory != '' || this.form.accessory != undefined) {
        let fileList = JSON.parse(this.form.accessory)
        fileList.map(item => {
          this.appendFileList.push({
            'name': item.name,
            'url': item.url,
            'type': this.creativeType(item.url),
            'progress': 100
          })
        })
      }
      getFinanceEntityList(row.invoiceMaker).then((res) => {
        const column = this.findObject(this.option.column, "entityId");
        column.dicData = res.data.data;
      })
      getFinanceEntityList(row.invoiceMaker).then((res) => {
        const column = this.findObject(this.option.column, "entityName");
        column.dicData = res.data.data;
      })

      // getFinanceItemList(this.form.id).then((res) => {
      //   this.financeItemList = res.data.data
      //   if (this.financeItemList.length == 0)
      //     this.financeItemList = [{id: "", detail: "", amount: ""}];
      // })
    },
    creativeType(url) {
      let urlTail = ((url != null && url.indexOf('.') >= 0) ?
        (url.substring(url.lastIndexOf('.') + 1)) : '').toLowerCase();

      let imgList = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      let videoList = ['mp4', 'mov', 'avi', 'mp3', 'ogg', 'rmvb', 'mkv']
      if (imgList.includes(urlTail)) {
        return 'image'
      } else if (videoList.includes(urlTail)) {
        return 'video'
      } else {
        return ''
      }
    },
    /**
     * 新增/编辑判断条件
     */
    optionRules() {
      this.option.column.map(item => {
        if (item.rules) {
          let rule = {[item.prop]: item.rules}
          this.rules = Object.assign(this.rules, rule)
        }
      })
    },
    init() {
      getReceivableCustomers().then(res => {
        this.receivableCustomerList = res.data.data
      })
      getInvoiceMakers().then(res => {
        this.invoiceMakerList = res.data.data
      })
      getCustomerList().then(res => {
        let column = this.findObject(this.option.column, "customerId");
        column.dicData = res.data.data;

        // column = this.findObject(this.option.column, "invoiceMaker");
        // column.dicData = res.data.data;
      })
      getEntityList(1, -1).then(res => {
        // this.invoiceMakerList2 = res.data.records
        let column = this.findObject(this.option.column, "invoiceMaker");
        // column = this.findObject(this.option.column, "invoiceMaker");
        column.dicData = res.data.data.records;
        console.log('dicdata', res.data.data.records)
      })
      getDept().then(res => {
        let column = this.findObject(this.option.column, "dept");
        column.dicData = res.data.data;
        this.deptList = res.data.data;
      })
    },
    getPaymentType(id) {
      if (id == 0) return "预付";
      if (id == 1) return "后付";
      if (id == 2) return "退税";
      if (id == 3) return "退款";
      if (id == 4) return "充值";
    },
    getProceedStatus(id) {
      if (id == 0) return "未处理";
      if (id == 1) return "已处理";
    },
    buildSearch() {
      this.queryForm.startCreateTime = ''
      this.queryForm.endCreateTime = ''
      this.queryForm.startUpdateTime = ''
      this.queryForm.endUpdateTime = ''
      this.queryForm.startPredictPaymentDate = ''
      this.queryForm.endPredictPaymentDate = ''
      this.queryForm.startActualPaymentDate = ''
      this.queryForm.endActualPaymentDate = ''
      this.queryForm.startOccurMonth = ''
      this.queryForm.endOccurMonth = ''

      if (this.createTime != null && this.createTime.length > 0) {
        this.queryForm.startCreateTime = this.createTime[0]
        this.queryForm.endCreateTime = this.createTime[1]
      }

      if (this.updateTime != null && this.updateTime.length > 0) {
        this.queryForm.startUpdateTime = this.updateTime[0]
        this.queryForm.endUpdateTime = this.updateTime[1]
      }

      if (this.predictPaymentDate != null && this.predictPaymentDate.length > 0) {
        this.queryForm.startPredictPaymentDate = this.predictPaymentDate[0]
        this.queryForm.endPredictPaymentDate = this.predictPaymentDate[1]
      }

      if (this.actualPaymentDate != null && this.actualPaymentDate.length > 0) {
        this.queryForm.startActualPaymentDate = this.actualPaymentDate[0]
        this.queryForm.endActualPaymentDate = this.actualPaymentDate[1]
      }

      if (this.occurMonth != null && this.occurMonth.length > 0) {
        this.queryForm.startOccurMonth = this.occurMonth[0]
        this.queryForm.endOccurMonth = this.occurMonth[1]
      }

      this.query = {...this.queryForm};
    },
    searchForm() {
      this.buildSearch();
      this.page.currentPage = 1
      this.onLoad(this.page)
    },
    /**
     * 关闭抽屉
     */
    handlerDrawerClose() {
      this.drawerVisible = false;
      // this.refreshChange()
    },
    handlerProgressDrawerClose() {
      this.progressDrawerVisible = false;
    },
    //清楚按钮函数
    emptyForm() {
      this.queryForm = {
        name: '',
        createUser: '',
        level: '',
        productName: '',
        phone: '',
        address: '',
        startDate: '',
        endDate: ''
      }
      this.createTime = []
      this.updateTime = [],
        this.occurMonth = [],
        this.predictPaymentDate = [],
        this.actualPaymentDate = [],
        this.searchForm();
    },
    handleProgressSubmit() {
      addProgress(this.selectionList[0].id, this.progressContent).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.progressDrawerVisible = false;
      }, error => {
        window.console.log(error);
      });
    },
    handleForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.drawerTitle === '新 增' || this.drawerTitle === '复 制') {
            this.rowSave();
          } else {
            this.rowUpdate();
          }
        }
      });
    },
    rowSave() {
      // let verified = true
      // this.financeItemList.map(item => {
      //   if (item.detail == '' || item.amount == '') {
      //     verified = false
      //   }
      // })
      // if (!verified) {
      //   this.$message({
      //     type: "error",
      //     message: "明细和金额不能为空!"
      //   });
      //   return
      // }
      this.form['accessory'] = JSON.stringify(this.getFileList());
      const form = _.cloneDeep(this.form)
      form.appIds = form.appIds.join(',')
      addReceivable(form, this.formatterAccountCostDetails()).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.drawerVisible = false;
        getReceivableCustomers().then(res => {
          this.receivableCustomerList = res.data.data
        })
      }, error => {
        window.console.log(error);
      });
    },
    rowUpdate() {
      if (this.drawerTitle == '编 辑') {
        this.form['accessory'] = JSON.stringify(this.getFileList());
        const form = _.cloneDeep(this.form)
        form.appIds = form.appIds.join(',')
        updateReceivable(form, this.formatterAccountCostDetails()).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.drawerVisible = false;
        }, error => {
          console.log(error);
        });
      }

    },
    view(item) {
      let type = item.url.substring(item.url.lastIndexOf('.') + 1, item.url.length)
      // console.log(type)
      if (type !== 'xlsx' && type !== 'xls') {
        this.$message.warning('只支持Excel文件预览')
        return
      }
      this.visble = true
      this.visbleURL = `https://view.officeapps.live.com/op/view.aspx?src=${item.url}`
      // console.log(item)
    },
    checkImage(v) {
      console.log(v)
      this.imageCheck = true
      this.imageUrl = v.url
    },
    handleQiniuDownload(file) {
      // window.open(file.url)
      // console.log(file)
      if (!file.url.startsWith('http')) {
        return;
      }
      if (!file.url.startsWith('https')) {
        let urlArr = file.url.split("://")
        if (urlArr.length < 2) {
          return;
        }
        file.url = "https://" + urlArr[1]
      }
      console.log(file)
      const that = this
      var xhr = new XMLHttpRequest()
      let urlTail = ((file.url != null && file.url.indexOf('.') >= 0) ? (file.url.substring(file.url.lastIndexOf('.') + 1)) : '').toLowerCase();

      let options = {}
      if (urlTail == 'mp4' || urlTail == 'mov') {
        options = {type: 'video/' + urlTail}
      } else if (urlTail != '') {
        options = {type: 'image/' + urlTail}
      } else {
        return
      }
      xhr.open('GET', file.url, true)
      xhr.responseType = 'arraybuffer'
      xhr.onload = function () {
        debugger
        if (xhr.readyState === 4 && xhr.status === 200) {
          that.btnTitle = '下载'
          that.isLoading = false
          const blob = this.response
          // 转换一个blob链接
          const u = window.URL.createObjectURL(new Blob([blob], options))
          const a = document.createElement('a')
          a.download = file.name + '.' + urlTail
          a.href = u
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        }
      }
      xhr.send()
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeReceivable(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      let deleteIds = [];
      this.selectionList.forEach(ele => {
        if (ele.funcFlag != 'used') {
          deleteIds.push(ele.id);
        }
      });
      if (deleteIds.length === 0) {
        this.$message.warning("请选择至少一条允许删除的客户数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeReceivable(deleteIds.join(","));
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    batchUpdateStatus() {
      this.statusValues = null
      if (this.selectionList.length === 0) {
        return this.$message.warning('请勾选数据')
      }
      this.batchChangeStatusVisible = true
    },
    async beforeOpen(type) {
      if (["edit", "view"].includes(type)) {
        this.currOpRowId = this.form.id;
        // await getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
    },
    searchReset() {
      this.emptyForm();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getReceivableList(page.currentPage, page.pageSize, Object.assign({}, params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    exportExcel(url, a, b, c) {
      console.log("返回的二进制流文件")
      axios.post(url, {id: a, fileType: b, badge: c}, {responseType: 'arraybuffer'}).then(function (res) {
        console.log("返回的二进制流文件", res)
        if (!res) return;
        //fileName:下载的文件名
        var fileName = decodeURIComponent(res.headers["content-disposition"].split("=")[1])
        let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'});

        // 针对ie浏览器
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          //非ie浏览器
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //常见下载的链接
          downloadElement.href = href;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href);  //释放blob对象
        }
      }).catch(function (error) {
        console.log(error);
      })

    },
    exportExcel11(url, a) {
      console.log("返回的二进制流文件")
      axios.post(url, {ids: a}, {responseType: 'blob'}).then(function (res) {
        console.log("返回的二进制流文件", res)
        if (!res) return;
        //fileName:下载的文件名
        var fileName = decodeURIComponent(res.headers["content-disposition"].split("=")[1])
        let blob = new Blob([res.data], {type: 'application/octet-stream'});

        // 针对ie浏览器
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          //非ie浏览器
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //常见下载的链接
          downloadElement.href = href;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href);  //释放blob对象
        }
      }).catch(function (error) {
        console.log(error);
      })

    },
    // exportInvoice1(type,ids) {
    //     var content=document.getElementById('aaaaaa');
    //     var aLink=document.createElement("a");
    //     content.appendHTML(aLink);
    //     let fileType='yes';
    //     if(type==='pdf'){
    //       if(ids.length==1){
    //         aLink.href="${ctx}/account/invoice/downloadPdfZip?ids="+ids[0]+"&type="+fileType;
    //       }else{
    //         // ids=ids.join(",")
    //         aLink.href="${ctx}/account/invoice/downloadPdfZip?ids="+ids+"&type="+fileType;
    //       }
    //     }
    //     window.open(aLink.href,'_target')
    // },
    exportInvoice() {
      this.exportExcel('/api/beetles-business/finance/receivable/exportInvoice', this.selectionList[0].id, this.invoiceFormat, this.currentSeal)
      // alert('aaa')
      // console.log(this.selectionList[0].id)
      // console.log(this.invoiceFormat)
      // console.log(this.currentSeal)
      // downloadInvoice(this.selectionList[0].id, this.invoiceFormat, this.currentSeal).then((res)=>{
      //
      // //   let fileName = res.headers['content-disposition'].split('=')[1]
      //   let fileName = "发票.pdf"
      //   //console.log(fileName)
      //   console.log(res)
      //   // 获取文件名
      //   let objectUrl = URL.createObjectURL(new Blob([res.data]))
      //   console.log(objectUrl)
      //   // 文件地址
      //   const link = document.createElement('a')
      //   link.download = fileName
      //   link.href = objectUrl
      //   link.click()
      // }).catch((err)=>{
      //   console.log(err);
      // })
    },
    handleExportInvoice() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择一条数据");
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning("仅支持下载单条数据发票！");
        return;
      }
      this.selectSealBox = true
    },
    viewReceivableProgress() {
      this.progressContent = ''
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择一条数据");
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning("只能查看一条数据");
        return;
      }
      this.progressView(this.selectionList[0])
    },
    handleSummary() {
      let invoiceAmountTotal = 0.0
      let actualAmountTotal = 0.0
      this.selectionList.forEach(row => {
        invoiceAmountTotal += (row.invoiceAmount == null ? 0 : parseFloat(row.invoiceAmount))
        actualAmountTotal += (row.actualAmount == null ? 0 : parseFloat(row.actualAmount))
      })
      let context = " 发票金额总计($):  " + Math.round(invoiceAmountTotal * 100) / 100
        + `<br/>` + " 实际到账金额总计($):  " + Math.round(actualAmountTotal * 100) / 100
      this.$alert(context, "求和结果", {
        confirmButtonText: "确定", dangerouslyUseHTMLString: true
      })
    },
    async handleExport() {
      let selectList = this.selectionList.map(item => item.id).join(',')
      const res = await exportExcel3({
        ids: selectList
      })
      let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
      let url = window.URL.createObjectURL(new Blob([res.data]))
      let link = document.createElement("a")
      link.style.display = "none"
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      // axios.post({
      //   url: '/api/beetles-business/finance/payable/export',
      //   responseType:"blob",
      // }).then(response=>{
      //   console.log(response)
      //   const res = response.data
      //   if (response.headers['content-type'] === "application/octet-stream;charset=utf-8") {
      //     let disposition = decodeURI(response.headers['content-disposition']);
      //     let fileName = disposition.split('=')[1];
      //     const a = document.createElement('a')
      //     const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      //     const url = URL.createObjectURL(blob)
      //     a.setAttribute('href', url)
      //     a.setAttribute('download', fileName)
      //     a.click()
      //     return
      //   }
      // })
      // axios.post('/api/beetles-business/finance/payable/export', {ids:this.selectionList[0].id},{
      //   responseType: 'blob' //返回的数据类型
      // })
      //   .then(res => {
      // console.log(response)
      // const res = response.data
      // if (response.headers['content-type'] === "application/octet-stream;charset=utf-8") {
      //   let disposition = decodeURI(response.headers['content-disposition']);
      //   let fileName = disposition.split('=')[1];
      //   const a = document.createElement('a')
      //   const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      //   const url = URL.createObjectURL(blob)
      //   a.setAttribute('href', url)
      //   a.setAttribute('download', fileName)
      //   a.click()
      //   return
      // }
      //     console.log(res, '返回数据列');
      //     const blob = new Blob([res.data], {
      //       type: 'application/vnd.ms-excel'
      //     });
      //     console.log(blob, '----------0990');
      //     const fileName = '短信列表.xlsx';
      //     const linkNode = document.createElement('a');
      //
      //     linkNode.download = fileName; //a标签的download属性规定下载文件的名称
      //     linkNode.style.display = 'none';
      //     linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
      //     document.body.appendChild(linkNode);
      //     linkNode.click(); //模拟在按钮上的一次鼠标单击
      //
      //     URL.revokeObjectURL(linkNode.href); // 释放URL 对象
      //     document.body.removeChild(linkNode);
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //   })
      // console.log(this.selectionList)
      // let selectList=[]
      // selectList=this.selectionList.map(item=>item.id)

      // this.exportExcel11('/api/beetles-business/finance/payable/export',this.selectionList[0].id)


      // this.$confirm("是否导出客户数据?", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => {
      //
      //   let tableData = {
      //     title: null,
      //     headers: [],
      //     rowList: [],
      //     bottom: [],
      //   };
      //   tableData.headers.push({data: '客户', style: 'text-align: right;'});
      //   tableData.headers.push({data: '发票名', style: 'text-align: right;'});
      //   tableData.headers.push({data: '开票方', style: 'text-align: right;'});
      //   tableData.headers.push({data: '账单月份', style: 'text-align: right;'});
      //   tableData.headers.push({data: '所属部门', style: 'text-align: right;'});
      //   tableData.headers.push({data: '付款类型', style: 'text-align: right;'});
      //   tableData.headers.push({data: '发票金额', style: 'text-align: right;'});
      //   tableData.headers.push({data: '实际金额', style: 'text-align: right;'});
      //   tableData.headers.push({data: '开票日期', style: 'text-align: right;'});
      //   tableData.headers.push({data: '回款天数', style: 'text-align: right;'});
      //
      //   this.selectionList.forEach(row => {
      //     let colList = [];
      //     colList.push({data: row.customerName, style: 'text-align: right;'});
      //     colList.push({data: row.invoiceName, style: 'text-align: right;'});
      //     // colList.push({data: (row.status === 0) ? '停止' : '活跃', style: 'text-align: right;'});
      //     colList.push({data: row.invoiceMakerName, style: 'text-align: right;'});
      //     colList.push({data: row.occurMonth, style: 'text-align: right;'});
      //     colList.push({data: row.dept, style: 'text-align: right;'});
      //     colList.push({data: row.$paymentType, style: 'text-align: right;'});
      //     colList.push({data: row.invoiceAmount, style: 'text-align: right;'});
      //     colList.push({data: row.actualAmount, style: 'text-align: right;'});
      //     colList.push({data: row.predictPaymentDate, style: 'text-align: right;'});
      //     colList.push({data: row.receivableDays, style: 'text-align: right;'});
      //     tableData.rowList.push(colList);
      //   });
      //   exportExcel('downloadExcel', tableData.title, tableData.headers, tableData.rowList, tableData.bottom, '客户数据表.xls');
      // });
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    // 设置默认开票方
    async setDefaultInvoiceMaker() {
      const {data: res} = await getEntityList(1, -1)
      this.invoiceMakerList2 = res.data.records
      if (this.invoiceMakerList2[0].name === 'ads4each') {
        this.form.invoiceMaker = this.invoiceMakerList2[0].id
        this.invoiceMakerChanged(this.invoiceMakerList2[0].id)
      }
    },
    // 获取APP列表
    async getAppSelectbyCostomer(val) {
      const {data: res} = await getAppSelectbyCostomer({
        customerId: val
      })
      const appIds = this.option.column.find(item => item.prop === 'appIds')
      this.$set(appIds, 'dicData', res.data)
      this.appList = res.data
      this.form.appIds = []
      this.form.invoiceAmount = ''
    },
    handleChangeApp(val) {
      // console.log(val, this.curAppIds)
      const dif = _.difference(val, this.curAppIds);
      this.curAppIds = val
      if (dif.length === 0) return
      const appId = dif[0]
      this.getAppSelectMap(appId)
      // this.$nextTick(() => {
      //   this.$refs[appId + 'table'][0].toggleAllSelection()
      //   this.$forceUpdate()
      // })
      // setTimeout(()=>{
      //   console.log('更新')
      //   this.$refs[appId + 'table'][0].toggleAllSelection()
      //   this.$forceUpdate()
      // },3000)
    },
    // 获取选择map
    async getAppSelectMap(appId) {
      this.appSelectMap[appId] = {data: {}}
      if (this.form.occurMonth) {
        const {data: res} = await getAccountCostDetails({
          appId,
          occurMonth: this.form.occurMonth
        })
        if (res.data.length > 0) {
          const appObj = res.data[0]
          appObj.byAll = appObj.byAll.map(item => {
            item.editCost = false
            item.editServiceFee = false
            item.editInvoiceAmount = false
            if (item.serviceFee === null) {
              item.serviceFee = 0
            }
            return item
          })
          appObj.byCountry = appObj.byCountry.map(item => {
            item.editCost = false
            item.editServiceFee = false
            item.editInvoiceAmount = false
            if (item.serviceFee === null) {
              item.serviceFee = 0
            }
            return item
          })
          this.appSelectMap[appId].data = appObj
        } else {
          this.appSelectMap[appId].data = {}
        }
        this.$nextTick(() => {
          this.$refs[appId + 'table'][0].toggleAllSelection()
          this.$forceUpdate()
        })
      }
    },
    handleChangeOccurMonth() {
      if (this.form.appIds && this.form.appIds.length > 0) {
        Promise.all(this.form.appIds.map(item => {
          return this.getAppSelectMap(item)
        }))
      }
    },
    handleBlurServiceFee(row) {
      row.editServiceFee = false
      this.countInvoiceAmount(row)
      this.totalInvoiceAmount()
    },
    handleBlurCost(row) {
      row.editCost = false
      this.countInvoiceAmount(row)
      this.totalInvoiceAmount()
    },
    handleBlurinvoiceAmount(row) {
      row.editInvoiceAmount = false
      this.totalInvoiceAmount()
    },
    changeIncludeServiceFee(row) {
      this.countInvoiceAmount(row)
      this.totalInvoiceAmount()
    },
    // 计算金额
    countInvoiceAmount(row) {
      // console.log(parseFloat(row.cost))
      if (row.includeServiceFee) {
        row.invoiceAmount = (parseFloat(row.cost) * (parseInt(row.serviceFee) / 100 + 1)).toFixed(2)
      } else {
        row.invoiceAmount = (parseFloat(row.cost) * (parseInt(row.serviceFee) / 100)).toFixed(2)
      }
    },
    // 按地区开票
    handleChangeAreaCheck(appId) {
      this.$nextTick(() => {
        this.$refs[appId + 'table'][0].toggleAllSelection()
        this.$forceUpdate()
      })
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },
    formatterAccountCostDetails() {
      return this.form.appIds.map(appId => {
        this.appSelectMap[appId].data.byAll.forEach(item => {
          item.isCheck = false
        })
        this.appSelectMap[appId].data.byCountry.forEach(item => {
          item.isCheck = false
        })
        this.appSelectMap[appId].data.multipleSelection.forEach(item => {
          item.isCheck = true
        })
        return this.appSelectMap[appId].data
      })
    },
    handleSelectionChange(val, appId) {
      this.appSelectMap[appId].data.multipleSelection = val
      this.$nextTick(() => {
        this.totalInvoiceAmount()
      })
    },
    async getAppSelectMapById() {
      const {data: res} = await getAccountCostDetails({
        financeReceivableId: this.form.id,
        appId: 0,
        occurMonth: 0
      })
      this.formatterAppSelectMap(res.data)
      console.log(this.form)
      this.$set(this.form, 'appIds', res.data.map(item => item.appId))
      this.form.appIds = res.data.map(item => item.appId)
      this.$nextTick(() => {
        res.data.forEach(app => {
          if (app.byCountryInvoice) {
            this.toggleSelection(app.byCountry.filter(item => item.isCheck), app.appId)
          } else {
            this.toggleSelection(app.byAll.filter(item => item.isCheck), app.appId)
          }
        })
      })
    },
    formatterAppSelectMap(arr) {
      this.appSelectMap = {}
      arr.forEach(appObj => {
        // this.appSelectMap[item.appId].
        appObj.byAll = appObj.byAll.map(item => {
          item.editCost = false
          item.editServiceFee = false
          item.editInvoiceAmount = false
          if (item.serviceFee === null) {
            item.serviceFee = 0
          }
          return item
        })
        appObj.byCountry = appObj.byCountry.map(item => {
          item.editCost = false
          item.editServiceFee = false
          item.editInvoiceAmount = false
          if (item.serviceFee === null) {
            item.serviceFee = 0
          }
          return item
        })
        this.appSelectMap[appObj.appId] = {data: appObj, query: {}}
      })
    },
    toggleSelection(rows, appId) {
      if (rows) {
        rows.forEach(row => {
          this.$refs[appId + 'table'][0].toggleRowSelection(row);
        });
      } else {
        this.$refs[appId + 'table'][0].clearSelection();
      }
    },
    findAppName(appId) {
      const res = this.appList.find(item => item.id === appId)
      if (res === undefined) {
        return ''
      } else {
        return res.name
      }
    },
    // 统计发票总额
    totalInvoiceAmount() {
      if (this.form.appIds && this.form.appIds.length > 0) {
        let total = parseFloat('0.00')
        this.form.appIds.forEach(appId => {
            if (this.appSelectMap[appId].data.multipleSelection && this.appSelectMap[appId].data.multipleSelection.length > 0) {
              this.appSelectMap[appId].data.multipleSelection.forEach(selection => {
                  total += parseFloat(selection.invoiceAmount)
                }
              )
            }

          }
        )
        console.log(total)
        this.$set(this.form, 'invoiceAmount', total.toFixed(2))
      }
    }
  }
};
</script>

<style lang="scss">
.hanDer {
  overflow: hidden;
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis
}

.search_form {
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}

.view-offer-table {
  margin-top: 40px;

  /deep/ .el-table td, .el-table th {
    padding: 9px 0;
  }
}

.comment-body {
  margin-top: 10px;
  margin-bottom: 30px;
  font-size: 14px;

  .comment-main {
    margin-bottom: 10px;
  }

  .comment-time {
    margin-top: 5px;
    color: #C9C9C9;

    * {
      margin-right: 15px;
    }
  }
}

.comment-header {
  display: flex;
  align-items: center;
}

.app-item-container {
  margin-bottom: 20px;
}
</style>
<style lang="scss" scoped>
/deep/ .current-op-row {
  background-color: #f5dab1;
}

/deep/ .el-input__inner {
  text-overflow: ellipsis;
}
</style>
